<template>
	<view class="warp">
		<view class="tab">
			<view @tap="tabChange(1)" class="tab-item">
				<text>
					{{routerInfo.ticketDate ? routerInfo.ticketDate.substring(5, routerInfo.ticketDate.length) : ''}}</text>
				<view class="tab-item-bottom-line" :class="{'tab-item-bottom-line-activ': activTab === 1}"/>
			</view>
			<view @tap="tabChange(2)" class="tab-item">
				<text>不同乘车点</text>
				<view class="tab-item-bottom-line" :class="{'tab-item-bottom-line-activ': activTab === 2}"/>
			</view>
		</view>
		<scroll-view scroll-y style="height: calc(100% - 320upx);">
			<view v-if="activTab === 1" class="passenger">
				<view class="block">
					<text>选择乘车点</text>
					<view class="ride-point-block">
						<view class="ride-point">
							<view class="point" style="background: #2697FF;"/>
							<view class="site-select">
								<text>{{`${routerInfo.fromCity}·`}}</text>
								<mftcc-select
									style="flex: 1;"
									name="statioId"
									:dataList="startSite" 
									text="stationName"
									:title="getSiteName(startSite, selectedRidePoint[0].startSiteId, '上车点')"
									v-model="selectedRidePoint[0].startSiteId" 
									@change="changeStartSite" />
							</view>
						</view>
						<view class="ride-point">
							<view class="point" style="background: #FF603F;"/>
							<view class="site-select">
								<text>{{`${routerInfo.endCity}·`}}</text>
								<mftcc-select
									style="flex: 1;"
									name="statioId"
									:dataList="endSite" 
									text="stationName"
									:title="getSiteName(endSite, selectedRidePoint[0].endSiteId, '下车点')"
									v-model="selectedRidePoint[0].endSiteId" 
									@change="changeStartSite" />
							</view>
						</view>
					</view>
				</view>
				<view class="block">
					<view 
						@tap="modalOpen()"
						 style="display: flex; flex-direction: row; justify-content: space-between;">
						<text class="title">添加乘车人</text>
						<view class="add-passenger-btn" @tap="modalOpen()">
							<text>{{selectedPassengers.length === 0 ? "添加" : "添加/修改"}}</text>
						</view>
					</view>
					<view 
						v-for="(item, index) in selectedPassengers"
						:key="index"
						class="passenger-item"
						style="padding: 0; background: #F3F4F5; border-radius: 16upx; margin-top: 10upx; padding-left: 10upx;">
						<image
							@click="removeSeat(index)"
							style="margin-right: 20upx;"
							src="../../static/icon_remove_red.png" 
							mode=""
						/>
						<view class="passenger-info" style="padding-top: 20upx; padding-bottom: 20upx; padding-top: 20upx;">
							<text style="font-size: 32rpx; font-weight: bold;">{{item.passengerName}}</text>
							<text style="font-size: 28rpx; color: #949699;">
								<text>身份证</text>
								<text>{{item.idCard}}</text>
							</text>
						</view>
					</view>
				</view>
			</view>
			<view v-if="activTab === 2" class="passenger">
				<view class="block">
					<view style="display: flex; flex-direction: row; justify-content: space-between;">
						<text class="title">添加乘车人</text>
						<view class="add-passenger-btn" @tap="modalOpen()">
							<text>{{selectedPassengers.length === 0 ? "添加" : "添加/修改"}}</text>
						</view>
					</view>
					<view style="background: #FFFFFF;">
						<view
							v-for="(item, tempIdnex) in selectedPassengers"
							:key="tempIdnex"
							class="ride-point-block" 
							style="background: #F7F7F7; padding: 20upx; border-radius: 16upx;">
							<view
								class="passenger-item"
								style="padding: 0;">
								<image
									@click="removeSeat(tempIdnex)"
									style="margin-right: 20upx;"
									src="../../static/icon_remove_red.png" 
									mode=""
								/>
								<view 
									class="passenger-info" 
									style="padding-top: 20upx; padding-bottom: 20upx; padding-top: 20upx;">
									<text style="font-size: 32rpx; font-weight: bold;">{{item.passengerName}}</text>
									<text style="font-size: 28rpx; color: #949699;">
										<text>身份证</text>
										<text>{{item.idCard}}</text>
									</text>
								</view>
							</view>
							<view class="ride-point" style="background: #FFFFFF;">
								<view class="point" style="background: #2697FF;"/>
								<view class="site-select">
									<text>{{`${routerInfo.fromCity}·`}}</text>
									<mftcc-select
										style="flex: 1;"
										name="statioId"
										:dataList="startSite" 
										text="stationName"
										:title="getSiteName(startSite, selectedRidePoint[tempIdnex].startSiteId, '上车点')"
										v-model="selectedRidePoint[tempIdnex].startSiteId" 
										@change="changeStartSite" />
								</view>
							</view>
							<view class="ride-point" style="background: #FFFFFF;">
								<view class="point" style="background: #FF603F;"/>
								<view class="site-select">
									<text>{{`${routerInfo.endCity}·`}}</text>
									<mftcc-select
										style="flex: 1;"
										name="statioId"
										:dataList="endSite"
										text="stationName"
										:title="getSiteName(endSite, selectedRidePoint[tempIdnex].endSiteId, '下车点')"
										v-model="selectedRidePoint[tempIdnex].endSiteId" 
										@change="changeStartSite" />
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="block">
				<text class="title">
					选择座位(添加乘车人后进行)
				</text>
				<view class="seatWarp">
					<image class="wheel" src="@/static/wheel.png">
					<view v-for="(seat, seatIndex) in seatList" :key='seatIndex' >
						<image 
							@tap="selectSeat(seat)"
							:class="seatClassList[seatIndex].seat"
							:src="getSeatStateImg(seat.state, seat.id)" />
						<text :class="seatClassList[seatIndex].seatNum">{{seatIndex + 1}}</text>
					</view>
				</view>
				<view class="tips">
					<view class="tips-item">
						<image 
							src="../../static/icon_tips_orange.png"
						/>
						<text>发车前60分钟可退票</text>
					</view>
					<view class="tips-item">
						<image 
							src="../../static/icon_tips_orange.png"
						/>
						<text>儿童需全价购票，暂不支持免费/半价票乘车</text>
					</view>
				</view>
			</view>	
			<view class="block" >
				<view style="display: flex; flex-direction: row; align-items: center; width: 100%;">
					<text style="margin-right: 15upx;">联系电话</text>
					<input 
						style="background: #F3F4F5; padding: 10upx; border-radius: 10upx;"
						type="number"
						v-model="phone" 
						placeholder="请输入" 
						maxlength="11" />
				</view>
				<view class="tips">
					<view class="tips-item">
						<image 
							src="../../static/icon_tips_orange.png"
						/>
						<text>用于接收取票信息</text>
					</view>
				</view>
			</view>
		</scroll-view>
		<view style="height: 195upx; background: #FFFFFF">
			<!-- <view style="height: 70upx; background: #FEF7EA; padding-left: 30upx;">
				<text style="color: #FF8103; font-size: 30upx; line-height: 70upx;">发车前1小时禁止退票</text>
			</view> -->
			<view
				style="height: 120upx; padding: 15upx; display: flex; flex-direction: row; justify-content: space-between; align-items: center;">
				<view style="padding-left: 30upx;">
					<text style="font-size: 28upx;">合计:</text>
					<text style="color: #FF603F; margin-left: 15upx; margin-right: 15upx;">
						<text style="font-size: 28upx;">￥</text>
						<text style="font-size: 34upx; font-weight: bold;">{{selectedPassengers.length * routerInfo.ticketPrice}}</text>
					</text>
					<text style="font-size: 28upx; color: #949699;">{{`共(${selectedPassengers.length})人`}}</text>
				</view>
				<view @tap="submit()" class="submit-btn" hover-class="submit-btn-hover-class">
					提交
				</view>
			</view>
		</view>
		<passenger-select-moadl
			@cancel="modalClose()"
			@determine="determine()"
			title="选择乘车人"
			:visible.sync="visible">
			<view style="height: 100%; display: flex; flex-direction: column; align-items: center;">
				<view  @click="toAddPassenger()" class="inset-passenger-btn">
					<image 
						src="../../static/icon_add_blue.png" 
					/>
					<text>添加乘车人</text>
				</view>
				<view style="flex: 1; width: 100%; padding: 10upx;">
					<checkbox-group @change="passengerCheckboxChange">
					    <view 
							v-for="(item, itemIndex) in passengerList" 
							:key="itemIndex" 
							class="passenger-item">
					        <checkbox
								color="#007AFF"
								:value="item.id"
								:checked="passengerIsSelected(item.id)"
								style="transform:scale(0.7)"/>
							<view @tap="selectedPassenger(item)" class="passenger-info">
								<text style="font-size: 32rpx; font-weight: bold;">{{item.passengerName}}</text>
								<text style="font-size: 28rpx; color: #949699;">
									<text>身份证</text>
									<text style="margin-left: 10upx;">{{item.idCard}}</text>
								</text>
							</view>
							<image
								@click="toAddPassenger(item.id)"
								src="../../static/icon_edit_grey.png" 
								mode=""
							/>
					    </view>
					</checkbox-group>
				</view>
				<view @tap="determine()" class="btn-submit">
					<text>完成</text>
				</view>
			</view>
		</passenger-select-moadl>
	</view>
</template>

<script>
	import api from '../../api';
	import PassengerSelectMoadl from './components/PassengerSelectMoadl.vue'
	export default {
		components: {
			PassengerSelectMoadl
		},
		data() {
			return {
				selectedSeatIds: [], // 选中的座位id
				selectedPassengers: [], // 选中的乘客
				tempSelectedPassengers: [], // 临时存储选中的乘客
				selectedRidePoint: [ // 选中的乘车点数据
					{startSiteId: '', endSiteId: ''}
				],
				phone: '',
				/**
				 * 基础数据
				 */
				activTab: 1, // 当前激活的tab
				visible: false,
				routerInfo: {}, // 班次详情
				passengerList: [], // 乘客列表
				seatList: [], // 座位信息
				endSite: [], // 下车点
				startSite: [], // 上车点
				seatClassList: [
					{
						seat: "select1",
						seatNum: "seatNum seatNum1"
					},
					{
						seat: "select2",
						seatNum: 'seatNum seatNum2'
					},
					{
						seat: "select3",
						seatNum: "seatNum seatNum3"
					},
					{
						seat: "select4",
						seatNum: "seatNum seatNum4"
					},
					{
						seat: "select5",
						seatNum: "seatNum seatNum5"
					},
					{
						seat: "select6",
						seatNum: "seatNum seatNum6"
					},
					{
						seat: "select7",
						seatNum: "seatNum seatNum7"
					},
					{
						seat: "select8",
						seatNum: "seatNum seatNum8"
					},
				]
			}
		},
		onLoad(option) {
			const routerInfo = JSON.parse(option.routerInfo);
			this.routerInfo = routerInfo;
			uni.setNavigationBarTitle({ title: `${routerInfo.fromCity} 一 ${routerInfo.endCity}` });
			this.queryByScheduleDatilId(routerInfo.id);
			this.queryByUserId();
		},
		methods: {
			// 查询班次信息
			async queryByScheduleDatilId(scheduleDetailId) {
				const { data } =  await api.route.queryByScheduleDatilId({scheduleDetailId});
				this.seatList = data?.seatVos || [];
				this.startSite = data?.startRoute || [];
				this.endSite = data?.endRoute || [];
				this.phone = data?.phone || '';
			},
			
			// 查询
			async queryByUserId() {
				const {data = []} = await api.user.queryByUserId();
				this.passengerList = data;
			},
			
			// 提交订单
			submit() {
				if(!this.sameRidePointChoiceCheck()) {
					return ;
				}
				if (this.activTab === 1) {
					if(!this.selectedRidePoint[0].startSiteId) {
						uni.showToast({
							title: '请选择上车点',
							duration: 1500,
							icon: 'none',
						});
						return ;
					}
					if(!this.selectedRidePoint[0].endSiteId) {
						uni.showToast({
							title: '请选择下车点',
							duration: 1500,
							icon: 'none',
						});
						return ;
					}
				}
				if (this.activTab === 2) {
					for(let index = 0; index < this.selectedPassengers.length; index++ ) {
						if(!this.selectedRidePoint[index]) {
							uni.showToast({
								title: `请选择第${index + 1}位乘客上车点与下车点`,
								duration: 1500,
								icon: 'none',
							});
							return ;
						}
						if(!this.selectedRidePoint[index].startSiteId) {
							uni.showToast({
								title: `请选择第${index + 1}位乘客上车点`,
								duration: 1500,
								icon: 'none',
							});
							return ;
						}
						if(!this.selectedRidePoint[index].endSiteId) {
							uni.showToast({
								title: `请选择第${index + 1}位乘客下车点`,
								duration: 1500,
								icon: 'none',
							});
							return ;
						}
					}
				}
				const passengerStationVos = this.selectedPassengers.map((passenger, index) => {
					return {
						passengerId: passenger.id,
						scheduleSeatId: this.selectedSeatIds[index],
						stationUpId: this.selectedRidePoint[index]?.startSiteId || this.selectedRidePoint[0]?.startSiteId,
						stationOffId: this.selectedRidePoint[index]?.endSiteId || this.selectedRidePoint[0]?.endSiteId,
					};
				});
				const params = {
					actualAmount: this.routerInfo.ticketPrice,
					orderType: 1,  //单类型：1班车订单、2带货订单、3包车订单 
					remark : '',
					scheduleDetailId: this.routerInfo.id,
					passengerStationVos,
					orderPhone: this.phone
				}
				uni.showModal({
					title: '提示',
					content: '发车前60分钟可退票',
					success: async (res) => {
					    if (res.confirm) {
					        uni.showLoading({ title:'支付中...' });
							const {code, data, msg = '异常请求'} = await api.order.createOrder(params);
							if(code == 200) {
								uni.requestPayment({
									provider: 'wxpay',
									timeStamp: data.timeStamp,
									nonceStr:data.nonceStr,
									package: data.package,
									signType: data.signType,
									paySign: data.paySign,
									success: (res) => {
										uni.hideLoading()
										// 跳转订单管理
										uni.reLaunch({
											url: '../order/order'
										});
									},
									fail: (res) => {
										uni.hideLoading()
										// 跳转订单管理
										uni.reLaunch({
											url: '../order/order'
										});
									}
								});
								
							}
							else{
								uni.hideLoading()
								uni.showToast({
									title: msg,
									duration: 1500,
									icon: 'none',
								});
							}
					    } 
						else if (res.cancel) {
					        console.log('用户点击取消');
					    }
					}
				});
			},
			
			// 同一乘车点规则校验
			sameRidePointChoiceCheck() {
				if(this.selectedPassengers.length === 0) { // 校验乘客
					uni.showToast({
						title: '请添加乘客',
						duration: 1500,
						icon: 'none',
					});
					return false;
				}
				if(this.selectedSeatIds.length === 0) { // 校验座位
					uni.showToast({
						title: '请选择座位',
						duration: 1500,
						icon: 'none',
					});
					return false;
				}
				if(this.selectedSeatIds.length < this.selectedPassengers.length) {
					uni.showToast({
						title: '请继续选择座位',
						duration: 1500,
						icon: 'none',
					});
					return false;
				}
				if(!this.phone) {
					uni.showToast({
						title: '请输入联系电话',
						duration: 1500,
						icon: 'none',
					});
					return false;
				}
				return true;
			},
			
			// 乘车人改变
			passengerCheckboxChange(e) {
				this.tempSelectedPassengers = this.passengerList.filter(passenger => e.detail.value.includes(`${passenger.id}`));
			},
			
			selectedPassenger(item) {
				if(this.tempSelectedPassengers.some(passenger => passenger.id === item.id)) {
					this.tempSelectedPassengers = this.tempSelectedPassengers.filter(passenger => passenger.id  !== item.id);
				} 
				else {
					this.tempSelectedPassengers.push(item);
				}	
			},
			
			// 移除乘车人
			removeSeat(subscript) {
				if(this.activTab === 2 && this.selectedRidePoint.length > 1) {
					this.selectedRidePoint = this.selectedRidePoint.filter((item, index) => index !== subscript);
				}
				this.selectedPassengers.splice(subscript, 1);
				this.selectedSeatIds.splice(subscript, 1);
			},
			
			toAddPassenger(id = "") {
				uni.navigateTo({
					url: `../my/addPassenger?id=${id}`
				})
			},
			
			// 选择座位
			selectSeat({id, state}) {
				if(state === 1) {
					uni.showToast({
						title: '该座位已锁定',
						duration: 1500,
						icon: 'none',
					});
					return;
				}
				if(this.selectedPassengers.length === 0) {
					uni.showToast({
						title: '请先选择乘车人',
						duration: 1500,
						icon: 'none',
					});
				}
 				if(this.selectedSeatIds.includes(id)) {
					this.selectedSeatIds = this.selectedSeatIds.filter(seat => seat !== id);
					return ;
				}
				
				if(this.selectedSeatIds.length < this.selectedPassengers.length) {
					this.selectedSeatIds.push(id);
				}
			},
			
			// 选择站点
			changeStartSite(e) {

			},
			
			// 改变tab
			tabChange(activ) {
				this.activTab = activ;
				if(activ === 1 && this.selectedRidePoint.length > 1) {
					this.selectedRidePoint.splice(1, this.selectedRidePoint.length);
				}
				if(activ === 2) {
					for (let i = 0; i < this.selectedPassengers.length; i++) {
						this.$set(this.selectedRidePoint, i, this.selectedRidePoint[i] || {startSiteId: '', endSiteId: ''})
					}
				}
			},
			
			// 乘车人弹窗关闭
			modalClose() {
				this.tempSelectedPassengers = [];
			},
			
			modalOpen() {
				this.tempSelectedPassengers = [...this.selectedPassengers];
				this.visible = true;
			},
			
			determine() {
				this.selectedPassengers = this.tempSelectedPassengers;
				if(this.activTab === 2) {
					for (let i = 0; i < this.selectedPassengers.length; i++) {
						this.$set(this.selectedRidePoint, i, this.selectedRidePoint[i] || {startSiteId: '', endSiteId: ''})
					}
				}
				this.visible = false;
			},
		},
		
		computed: {
			getSeatStateImg() {
				return (state, seatId) => {
					if(state === 1) {
						return '../../static/selected_gray.png';
					}
				
					if(this.selectedSeatIds.includes(seatId)) {
						return '../../static/selected.png';
					}
					return '../../static/select.png';
				}
			},
			passengerIsSelected() {
				return (passengerId) => {
					return this.tempSelectedPassengers.some(passenger => passenger.id === passengerId);
				}
			},
			getSiteName() {
				return (siteList = [], siteId, title = '') => {
					if(!siteId) {
						return `点击选择${title}`;
					}
					const site =  siteList.find(site => site.statioId === siteId);
					return site?.stationName || '';
				}
			}
		}
	}
</script>

<style lang="scss">
	.warp {
		height: 100%;
		background: linear-gradient(to bottom, #2697FF 0%, #F7F7F7 30%);
		.tips {
			display: flex; 
			flex-direction: row;
			justify-content: space-between;
			margin-top: 20upx;
			.tips-item {
				display: flex;
				flex-direction: row;
				align-items: center;
				color: #FF8103;
				font-size: 20upx;
				image {
					width: 30upx;
					height: 30upx;
					margin-right: 10upx;
				}
			}
		}
		.tab {
			display: flex;
			flex-direction: row;
			height: 100upx;
			.tab-item {
				display: flex;
				flex-direction: column;
				justify-content: space-around;
				align-items: center;
				text-align: center;
				flex: 1;
				font-size: 34rpx;
				color: #FFFFFF;
			}
			.tab-item-bottom-line {
				height: 10upx;
				width: 100upx;
				border-radius: 10upx;
			}
			.tab-item-bottom-line-activ {
				background: #FFFFFF;
			}
		}
		.passenger {
			.ride-point-block {
				background: #F3F4F5;
				border-radius: 16upx;
				margin-top: 20upx;
				.ride-point {
					padding: 20upx;
					display: flex;
					flex-direction: row;
					justify-content: center;
					align-items: center;
					justify-content: space-between;
					height: 100upx;
					background: #F3F4F5;
					border-radius: 16upx;
					.site-select {
						display: flex; 
						flex-direction: row;
						flex: 1;
						align-items: center;
					}
					.point {
						width: 20upx;
						height: 20upx;
						border-radius: 50%;
						margin-right: 10upx;
					}
				}
			}
		}
		.block {
			background: #FFFFFF;
			padding: 20upx;
			margin-left: 20upx;
			margin-right: 20upx;
			border-radius: 16upx;
			margin-bottom: 15upx;
		}
		.add-passenger-btn {
			border: solid 1upx #2697FF;
			color: #2697FF;
			width: 200upx;
			height: 60upx;
			border-radius: 10upx;
			text-align: center;
			line-height: 60upx;
			padding-right: 20upx;
			padding-left: 20upx;
			font-size: 30rpx;
		}
		.inset-passenger-btn {
			width: 90%;
			display: flex;
			flex-direction: row;
			justify-content: center;
			align-items: center;
			background: #F2F9FF;
			height: 100upx;
			border-radius: 50upx;
			image {
				width: 50upx;
				height: 50upx;
				margin-right: 10upx;
			}
			text {
				color: #2697FF;
				font-size: 32rpx;
			}
		}
		.passenger-item {
			display: flex; 
			flex-direction: row;
			justify-content: space-between; 
			align-items: center;
			border-bottom: solid 1upx #EFEFEF;
			padding: 20upx;
			image {
				width: 40upx;
				height: 40upx;
			}
			.passenger-info {
				height: 100upx;
				display: flex;
				flex-direction: column;
				justify-content: space-between; 
				display: flex;
				flex: 1;
				flex-direction: column;
			}
		}
		.btn-submit {
			width: 90%; 
			margin-bottom: 10upx; 
			height: 90upx; 
			background: #2697FF;
			border-radius: 16upx; 
			display: flex; 
			flex-direction: row; 
			align-items: center; 
			justify-content: center;
			color: #FFFFFF;
		}
		.submit-btn {
			display: flex;
			flex-direction: row;
			justify-content: center;
			align-items: center;
			padding: 20upx;
			background: linear-gradient(to right, #FF9C4E, #FF603F);
			color: #FFFFFF;
			border-radius: 8upx;
			width: 25%;
		}
		.submit-btn-hover-class {
			opacity: 0.8;
		}
		.seatWarp {
			height: 270rpx;
			background: #F3F4F5;
			margin-top: 20rpx;
			border-radius: 20rpx;
			border:1px solid #EEEEEE;
			position: relative;
	
			text {
				position: absolute;
				color: #000000;
			}
			.title {
				top: 20rpx;
				left: 20rpx;
				font-weight: 800;
				font-size: 40rpx;
			}
	
			image {
				width: 45rpx;
				height: 45rpx;
				position: absolute;
			}
			.wheel {
				top: 185rpx;
				left: 5%;
			}
			.seatNum {
				position: absolute;
				font-size: 24rpx;
			}
			.select1 {
				top: 50rpx;
				left: 5%;
			}
			.seatNum1 {
				top: 55rpx;
				left: 15%;
			}
			.select2 {
				top: 120rpx;
				left: 42%;
			}
			.seatNum2 {
				top: 125rpx;
				left: 50%;
			}
			.select3 {
				top: 185rpx;
				left: 42%;
			}
			.seatNum3 {
				top: 190rpx;
				left: 50%;
			}
			.select4 {
				top: 120rpx;
				left: 60%;
			}
			.seatNum4 {
				top: 125rpx;
				left: 68%;
			}
			.select5 {
				top: 185rpx;
				left: 60%;
			}
			.seatNum5 {
				top: 190rpx;
				left: 68%;
			}
			.select6 {
				top: 50rpx;
				left: 78%;
			}
			.seatNum6 {
				top: 55rpx;
				left: 86%;
			}
			.select7 {
				top: 120rpx;
				left: 78%;
			}
			.seatNum7 {
				top: 125rpx;
				left: 86%;
			}
			.select8 {
				top: 185rpx;
				left: 78%;
			}
			.seatNum8 {
				top: 190rpx;
				left: 86%;
			}
		}
	}
</style>
